package com.example.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import com.example.util.RedisUtil;
import com.example.util.RespCode;
import com.example.util.RespEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;
/**请求拦截 */
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getServletPath().equals("/insertMessage") || request.getServletPath().equals("/register")){
            return true;
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            RespEntity resp =new RespEntity(RespCode.TOKENNO);
            response.getWriter().write(JSON.toJSONString(resp));
            response.getWriter().flush();
            return false;
        }
        /**
         * 判断token是否在redis缓存中
         */
        if( !redisUtil.hasKey(token)){
            RespEntity resp =new RespEntity(RespCode.TOKENERROR);
            response.getWriter().write(JSON.toJSONString(resp));
            response.getWriter().flush();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}